from flask import Blueprint, request, jsonify
from flask_login import login_required, current_user
from models import Category, Post
from extensions import db
from sqlalchemy import desc
import logging

logger = logging.getLogger('Personal_Blog_System')

# 创建分类API蓝图
category_api = Blueprint('category_api', __name__, url_prefix='/api/categories')

@category_api.route('/', methods=['GET'])
def get_categories():
    """获取分类列表"""
    try:
        include_stats = request.args.get('include_stats', 'false').lower() == 'true'
        
        categories = Category.query.filter_by(is_active=True).order_by(Category.sort_order, Category.name).all()
        
        categories_data = []
        for category in categories:
            category_data = {
                'id': category.id,
                'name': category.name,
                'description': category.description,
                'color': category.color,
                'parent_id': category.parent_id,
                'sort_order': category.sort_order,
                'created_at': category.created_at.isoformat(),
                'updated_at': category.updated_at.isoformat()
            }
            
            if include_stats:
                # 统计文章数量
                post_count = Post.query.filter_by(category_id=category.id, status='published').count()
                category_data['post_count'] = post_count
            
            categories_data.append(category_data)
        
        return jsonify({'success': True, 'data': categories_data})
        
    except Exception as e:
        logger.error(f"获取分类列表失败: {str(e)}")
        return jsonify({'success': False, 'message': '获取分类列表失败'}), 500

@category_api.route('/<int:category_id>', methods=['GET'])
def get_category(category_id):
    """获取单个分类"""
    try:
        category = Category.query.get_or_404(category_id)
        
        category_data = {
        'id': category.id,
        'name': category.name,
        'description': category.description,
            'color': category.color,
            'parent_id': category.parent_id,
            'sort_order': category.sort_order,
            'is_active': category.is_active,
            'created_at': category.created_at.isoformat(),
            'updated_at': category.updated_at.isoformat()
        }
        
        return jsonify({'success': True, 'data': category_data})
        
    except Exception as e:
        logger.error(f"获取分类失败: {str(e)}")
        return jsonify({'success': False, 'message': '获取分类失败'}), 500

@category_api.route('/', methods=['POST'])
@login_required
def create_category():
    """创建分类"""
    try:
        data = request.get_json()
        
        # 验证必填字段
        if not data.get('name'):
            return jsonify({'success': False, 'message': '分类名称是必填字段'}), 400
        
        # 验证parent_id（如果提供）
        parent_id = data.get('parent_id')
        if parent_id is not None:
            parent = Category.query.get(parent_id)
            if not parent:
                return jsonify({'success': False, 'message': '父分类不存在'}), 400
        
        # 创建分类
        category = Category(
            name=data['name'],
            description=data.get('description', ''),
            color=data.get('color', '#007bff'),
            parent_id=parent_id,
            sort_order=data.get('sort_order', 0)
        )
        
        db.session.add(category)
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '分类创建成功',
            'data': {'id': category.id}
        }), 201
        
    except Exception as e:
        logger.error(f"创建分类失败: {str(e)}")
        db.session.rollback()
        return jsonify({'success': False, 'message': '创建分类失败'}), 500

@category_api.route('/<int:category_id>', methods=['PUT'])
@login_required
def update_category(category_id):
    """更新分类"""
    try:
        category = Category.query.get_or_404(category_id)
        data = request.get_json()
        
        # 更新字段
        if 'name' in data:
            category.name = data['name']
        
        if 'description' in data:
            category.description = data['description']
        
        if 'color' in data:
            category.color = data['color']
        
        if 'parent_id' in data:
            parent_id = data['parent_id']
            # 防止循环引用：不能将自己设为父分类，也不能将自己的子分类设为父分类
            if parent_id is not None:
                if parent_id == category_id:
                    return jsonify({'success': False, 'message': '不能将分类设为自身的父分类'}), 400
                # 检查是否会形成循环：从新的父分类向上遍历，看是否包含当前分类
                def would_create_cycle(current_id, new_parent_id):
                    """检查将current_id的父分类设为new_parent_id是否会形成循环"""
                    current = Category.query.get(new_parent_id)
                    if not current:
                        return False
                    # 向上遍历父分类链
                    visited = set()
                    while current and current.id not in visited:
                        if current.id == current_id:
                            return True  # 发现循环
                        visited.add(current.id)
                        if current.parent_id:
                            current = Category.query.get(current.parent_id)
                        else:
                            break
                    return False
                
                if would_create_cycle(category_id, parent_id):
                    return jsonify({'success': False, 'message': '不能将子分类设为父分类，这会形成循环引用'}), 400
            
            category.parent_id = parent_id
        
        if 'sort_order' in data:
            category.sort_order = data['sort_order']
        
        if 'is_active' in data:
            category.is_active = data['is_active']
        
        db.session.commit()
        
        return jsonify({'success': True, 'message': '分类更新成功'})
        
    except Exception as e:
        logger.error(f"更新分类失败: {str(e)}")
        db.session.rollback()
        return jsonify({'success': False, 'message': '更新分类失败'}), 500

@category_api.route('/<int:category_id>', methods=['DELETE'])
@login_required
def delete_category(category_id):
    """删除分类"""
    try:
        category = Category.query.get_or_404(category_id)
        
        # 检查是否有子分类
        if Category.query.filter_by(parent_id=category_id).first():
            return jsonify({'success': False, 'message': '无法删除包含子分类的分类'}), 400
        
        # 检查是否有文章使用此分类
        if Post.query.filter_by(category_id=category_id).first():
            return jsonify({'success': False, 'message': '无法删除包含文章的分类'}), 400
        
        db.session.delete(category)
        db.session.commit()
        
        return jsonify({'success': True, 'message': '分类删除成功'})
        
    except Exception as e:
        logger.error(f"删除分类失败: {str(e)}")
        db.session.rollback()
        return jsonify({'success': False, 'message': '删除分类失败'}), 500
